const gulp = require("gulp");
const babel = require('gulp-babel');
const spritesmith = require("gulp.spritesmith");
const vinylBuffer = require("vinyl-buffer");
const pngquant = require("imagemin-pngquant");
const uglify = require("gulp-uglify");
const rename = require('gulp-rename');
const concat = require("gulp-concat");
const glob = require("glob");
const path = require("path");
const _config = require('./build/config');

// 生成公共的雪碧图
gulp.task('common_sprite', function () {
    var dirs = glob.sync(__dirname + `/src/sprites/*/`);
    dirs.forEach(basename => {
        basename = path.basename(basename);
        let spriteData = gulp.src(`./src/sprites/${basename}/*.png`)
            .pipe(spritesmith({
                imgName: `sprite_${basename}.png`,      // 生成的图片
                cssName: `sprite_${basename}.scss`,    // 生成的sass文件
                padding: 10,                         // 图标之间的距离
                algorithm: "top-down",               // 图标的排序方式
                spritestamp: true
            }))
        spriteData.pipe(gulp.dest(`src/sprites`));
    });
});

// 生成特定项目的雪碧图
gulp.task('sprite', function () {
    var dirs = glob.sync(__dirname + `/src/project_${_config.project}/sprites/*/`);
    dirs.forEach(basename => {
        basename = path.basename(basename);
        let spriteData = gulp.src(`./src/project_${_config.project}/sprites/${basename}/*.png`)
            .pipe(spritesmith({
                imgName: `sprite_${basename}.png`,      // 生成的图片
                cssName: `sprite_${basename}.scss`,    // 生成的sass文件
                padding: 10,                         // 图标之间的距离
                algorithm: "top-down",               // 图标的排序方式
                spritestamp: true
            }))
        spriteData.pipe(gulp.dest(`src/project_${_config.project}/sprites/`));
    });
});

/* libs.bundle.js 文件打包 */
gulp.task('libs', function () {
    gulp
    .src('src/plugins/libs/*.js')               // 要合并的文件
    .pipe(concat('libs.bundle.js'))  // 合并后命名为 "libs.bundle.js"
    .pipe(uglify({
        warnings: false,
        ie8: true,
    }))  
    .pipe(gulp.dest('src/plugins'));     // 输出路径
});

gulp.task("default", ["sprite"]);